Macromedia Flex Article

Building a Server Dashboard Application with ColdFusion-Powered Flex


Table of Contents

  1. Introduction
  2. So, What Exactly Is Flex?
  3. ColdFusion as a Flex Back End
  4. ColdFusion-Generated Flex
  5. Where To Use Flex
  6. Trying Flex
  7. Where to Go From Here

Trying Flex

To demonstrate Flex and ColdFusion in perfect harmony, I'll guide you in building a dashboard application. This is a very simple application, but it is a useful one. I originally wrote it for my own use and it demonstrates much of what I've already discussed.

The application is a ColdFusion dashboard. With it, developers can monitor their ColdFusion Server settings: defined data sources and their availability, queue request time, server load, defined mappings, SERVER scope contents, and more. Of course, Flex has no knowledge of ColdFusion specifically, and so the application has two distinct parts to it, a ColdFusion side and a Flex side:

  • cfdb.cfc is a ColdFusion component which exposes all of this information through web service calls. Place this file in any folder under the web root for your ColdFusion server. Note: Make sure you know the URL to it. You'll need to refer to it in the MXML code.
  • cfdb.mxml is the Flex MXML which defines the user interface for the application. Place this file in any folder under the Flex application root.
  • struct2tree.as is an ActionScript file that defines functions that cfdb.mxml needs; placed in the same folder as cfdb.mxml.

You can download these files in the sample files archive at the beginning of this tutorial.

For simplicity's sake, this application uses the first of the two integration methods described previously (ColdFusion as a Flex Back End). That is, you must put the CFC file on a ColdFusion server, but that doesn't have to be the Flex server; ColdFusion doesn't have to be running on the Flex server for this tutorial.

Note: This application is intended to be used on secure and trusted environments only. You'd never want to expose this much information on public facing servers.

The ColdFusion Dashboard Features a Tab Style Interface

Figure 5 shows a sample screen shot. As you can see, the ColdFusion Dashboard features a series of tabs, each of which provides different ColdFusion server information.

The ColdFusion dashboard features a tab style interface

Figure 5. The ColdFusion dashboard features a tab style interface

There are five tabs in the dashboard:

  • Stats displays server stats reported by the ColdFusion GetMetricData() function.
  • Server displays the contents of the ColdFusion SERVER scope.
  • Configuration displays several settings defined in the ColdFusion Administrator.
  • Data Sources lists all defined data sources and whether or not they are available.
  • Mappings displays the mappings in use by the ColdFusion server.

The tabs and contents are the ones that I needed for my own development. Adapt the application as best suits you using the techniques described below.

The cfdb.cfc file is a ColdFusion component that exposes five methods, one for each of the Dashboard tabs, as web services methods. The code is not complicated, but it is long, and so I'll not list it all here inline. However, you may download it from the beginning of this tutorial, in the Requirements section.

The method to populate the Server tab is very simple, it contains a CFRETURN tag which returns the entire SERVER scope:

<!--- Get SERVER scope --->
<CFFUNCTION NAME="GetServerData"
		RETURNTYPE="struct"
 		ACCESS="remote"
		OUTPUT="no">
	<!--- Return SERVER --->
 	<CFRETURN SERVER>
</CFFUNCTION>

Other methods are a bit more complicated. For example, the method to populate the Mappings tab calls the ColdFusion Service Factory and then formats the results as a ColdFusion query:

<!--- Get mappings --->
<!--- Get mappings --->
<CFFUNCTION NAME="GetMappings"
	RETURNTYPE="query"
 	ACCESS="remote"
 	OUTPUT="no">
 
<!--- Define returned query --->
<CFSET VAR results=QueryNew("alias,path")>

<!--- Get "factory" --->
<CFSET VAR fObj=CreateObject("JAVA", "coldfusion.server.ServiceFactory")>

<!--- Get runtime service --->
<CFSET VAR rtService=fObj.getRuntimeService()>
<!--- Get mappings --->
<CFSET VAR mappings=rtService.getMappings()>
<!--- Loop through data sources --->
<CFLOOP COLLECTION="#mappings#" ITEM="i">
	<!--- Add to query --->
	<CFSET QueryAddRow(results)>
	<CFSET QuerySetCell(results, "alias", i)>
	<CFSET QuerySetCell(results, "path", mappings[i])>
</CFLOOP>

<!--- Return query --->
<CFRETURN results>

</CFFUNCTION>

I will not walk through all of this code here, but one technique worth noting is that you should return data in as simple of a format as possible. The code in GetMappings() obtains a structure from the Service factory, but then converts it into a query as working with queries; it is easier for displaying grid-type data (this is true of any ColdFusion code, not just code that Flex will consume).

All of the five methods in component cfdb.cfc accept no parameters, they only return data. You should probably write a simple CFML file to invoke each of these, dumping the output to verify that they work properly, before writing the Flex client.

The Flex Client Code

I've already explained that Flex applications are written in MXML, but this is actually not entirely true. Flex applications are written in MXML, an XML-based language, and ActionScript 2, an object-oriented scripting language that Flash uses. In fact, code written in MXML automatically generates ActionScript source code which is then compiled into a Flash SWF.

Why is this important? Because it means that your Flex applications can contain both MXML tags and ActionScript as in the examples below.

Open cfdb.mxml, which is part of dashboard.zip from the Requirements section. The cfdb.mxml is the core Flex application. I would have listed the entire code, but it is too long. As such, I've explained the code in snippets, below:

MXML is an XML language, and MXML pages must start with the XML header:

<?xml version="1.0"?>

The <mx:Applciation> tag defines the application, and likewise, the entire application is between the opening and closing <mx:Application> and </mx:Application)> tags:

<mx:Application marginBottom="5"
	marginLeft="5"
	marginTop="5"
	marginRight="5"
	initialize="update()"
	
xmlns:mx="http://www.macromedia.com/2003/mxml"
	width="500"
	height="400">

The above code defines the size of the application in pixels, margins, and the location of the MXML language definition. I'll come back to the "initialize" attribute shortly.

The application calls the CFC methods as web services; the application defines these services using the <mx:WebService> tag:

<!-- Define Web Service -->
<mx:WebService id="dbSvc" wsdl="http://localhost:8500/cfdb/cfdb.cfc?wsdl"
	showBusyCursor="true">
	<mx:operation name="GetStats" />
	<mx:operation name="GetServerData" />
	<mx:operation name="GetConfig" />
	<mx:operation name="GetDataSources" />
</mx:WebService>

The wsdl attribute is the CFC WSDL URL. Change the path if needed. The showBusyCursor="true" attribute specifies to Flex that the mouse cursor should change to a stopwatch when the application processes web service calls; this provides visual feedback to the customer.

The GetServerData() method returns a structure. The application populates a tree in the Server tab that has a specific required format; thus, the code must convert a ColdFusion structure into XML so the tree control can use it. With Flex, you can put code into external files, and include them using the <mx:Script> tag; this tag is functionally similar to the ColdFusion CFINCLUDE tag. The following line of code includes the struct2tree.as file, which contains functions that perform the required conversion.

Note: I won't walk through the code in struct2tree.as in this article, but you may browse it yourself. It is a nice demonstration of ActionScript recursion.

<mx: Script source="struct2tree.as" />

The MXML <mx:Script> tag has another use too. With the <mx:Script> tag, developers can embed ActionScript right inside of MXML pages. The <mx:Script> block below defines two functions, the yesNoFormat() function and the update() function. The yesNoFormat() function is much like the CFML function which has the same name; here, it too returns a string "Yes" or "No" for boolean values.

// yesNoFormat() function
function yesNoFormat(bool) {
	var result:String;
	if (bool)
		result="Yes"
	else
		result="No"
	return result;
}

The update() function calls all of the five defined web service methods to update the display.

// update() all Web Service calls function
function update() {
	dbSvc.GetStats();
	dbSvc.GetServerData();
	dbSvc.GetConfig();
	dbSvc.GetDataSources();
	dbSvc.GetMappings();
}

The initialize="update()" attribute in the <mx:Application> tag mentioned previously triggers Flex to call the update() function automatically at application startup.

Next comes a bindings section in the file, but I'll skip that for now and come back to it shortly.

Next comes the UI itself. First is a title bar:

<!-- Title box -->
<mx:HBox>
   <!-- Title -->
   <mx:Label widthFlex="1"
             text="ColdFusion Dashboard"
             color="#FFFFFF"
             fontSize="20"  />
   <!-- Update button -->
   <mx:Button label="Update"
              click="update()" />
</mx:HBox>

The title text is defined in a horizontal box, so that contents within it are displayed side-by-side. The <mx:Label> tag is used to display a label (the title), and <mx:Button> defines a button that calls the update() function when a user presses it.

Note: Unlike in HTML, you cannot place text arbitrarily on a page, which is why you must use a tag to display title text.

The dashboard uses a tab interface, defined as follows:

<!-- Main screen -->
<mx:TabNavigator>
...
</mx:TabNavigator>

The individual tabs are defined in between <mx:TabNavigator> and </mx:TabNavigator> tags.

 The Data Sources tab uses a DataGrid to display data source information

Figure 6. The Data Sources tab uses a DataGrid to display data source information

I am not going to walk through every line of code here, as much is repeated. But a good simple tab to start with is the Data Sources tab (Figure 6):

<!-- Data Sources tab -->
<mx:HBox label="Data Sources">
	<!-- Data sources grid -->
  <mx:DataGrid id="dsGrid"
                editable="false"
                heightFlex="1"
                widthFlex="1"*gt;
      <mx:columns>
         <mx:Array>
            <mx:DataGridColumn headerText="Name"
                               columnName="name" />
            <mx:DataGridColumn headerText="Driver"
                               columnName="driver" />
            <mx:DataGridColumn headerText="Verified"
                               columnName="verified" />
         </mx:Array>
      </mx:columns>
   </mx:DataGrid>
</mx:HBox>

The code defines the actual tab using another box, the label of which is used as the tab text. The <mx:DataGrid> tag defines the data grid; it is named using the id attribute. Note that names must be unique. By default, all data provided to a grid displays (this is preferable for your app) in the sequence that the application returns the data (this is not preferable for the user experience). So rather then using defaults, you define the array of columns, and enumerate the individual columns using the <mx:DataGridColumn> tag, the headerText (the column title), and the columnName (actual retrieved column name) for each. That is all you need to define the data grid. But how does data actually get into the grid? That is where those bindings come in; I'll get to those shortly.

You create the Mappings tab in exactly the same way.

Note: As an XML language, you must close all MXML tags, either with an end tag, or with a trailing slash (/).

The Configuration tab (Figure 7) uses a <mx:Grid> tag—not to be confused with the data grid—to specifically align the element. The <mx:Grid> tag is similar to the <TABLE> tag in HTML, the <mx:GridRow> tag is like the HTML <TR> tag, and the <mx:GridItem> is like the HTML <TD> tag. You use these tags to lay out all of the displayed data.

The Configuration tab uses a Grid to align text

Figure 7. The Configuration tab uses a Grid to align text

The Server tab displays the SERVER scope contents in a tree, which you define using the <mx:Tree> tag. When a user selects a tree member, the application displays the value in a TextArea box below.

The Stats tab uses a DataGrid with a TextArea box below to display stat descriptions

Figure 8. The Stats tab uses a DataGrid with a TextArea box below to display stat descriptions

The Stats tab is similar to the Data Source tab, but it contains a text area box at the bottom, which is populates with a description of the currently selected stat in the grid:

<!-- Stats tab -->
<mx:VBox label="Stats">
   <!-- Stats grid -->
   <mx:DataGrid id="statsGrid"
                editable="false"
                heightFlex="1"
                widthFlex="1">
      <mx:columns>
         <mx:Array>
            <mx:DataGridColumn headerText="Property"
                               columnName="property" />
            <mx:DataGridColumn headerText="Vaue"
                               columnName="value" />
         </mx:Array>
      </mx:columns>
   </mx:DataGrid>
   <!-- Grid item description -->
   <mx:TextArea wordWrap="true"
                id="statDesc" 
                editable="false"
                height="50"
                widthFlex="1" />
</mx:VBox>

How does the application update the <mx:TextArea> box at the bottom of the screen as a grid selection changes? And for that matter, how does any of the data that the web service returns get into the appropriate UI controls? Now I'll go back and look at the <mx:Binding> tags I skipped before.

Bindings are connections between controls. If you have ever used Microsoft Excel, you'll be familiar with the concept. Cells in a spreadsheet can refer to other cells so that changes and updates are automatically propagated to other cells as needed. Bindings work the same way. They associate a source with a destination and ensure that the destination is kept up to date as source contents change.

Bindings in Flex may be defined right inside of controls, as seen here:

<mx:DataGrid id="statsGrid"
             editable="false"
             heightFlex="1"
             widthFlex="1"
             dataProvider="{dbSvc.GetStats.result}">

The dataProvider attribute refers to the result of the GetStats method, so that anytime GetStats returns data, the data grid updates automatically.

Note: Flex uses { and } to delimit expressions in the same way as CFML uses the pound sign (#).

Explicit binding works well, but when there are lots of bindings to lots of controls, all of those references can get hard to manage. In addition, binding this way make it impossible to bind a single control to multiple providers.

An alternate way to specify bindings is using the <mx:Binding> tag. cfdb.mxml has a whole series of bindings defined, starting with:

<!-- Define the bindings -->
<mx:Binding source="dbSvc.GetStats.result"
            destination="statsGrid.dataProvider" />

The <mx:Binding> tag takes a source and a destination, and ensures that if a change occurs in the source, that that change is propagated to the specified destination. The rest of the bindings work the same way, binding a source (some formatted using functions, including the yesNoFormat() and struct2tree() functions) to destinations.

Note: You can define web services, bindings, scripts, and so forth, anywhere in your application, however, you may want to organize them as in cfdb.mxml.

And that is all there is to it. Each time the update() method executes—when a user clicks the Update button or the application starts—Flex makes five web service calls to five defined methods. Each time a web service call returns data—which may occur while Flex requests other Web Service calls—the bindings route that data to the appropriate UI destination.

Note: When you browse cfdb.mxml in your browser, click the Update button each time you want to update the display. One useful enhancement would be to include timer code that executes the update() function on scheduled intervals. As there is no MXML timer control, this would involve writing ActionScript code, which is beyond the scope of this article.